/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * VentanaPrincipal.java
 *
 * Created on 13/11/2012, 11:05:51 AM
 */
package com.proffline.gui;

import com.proffline.tareas.ProgramadorTareas;
import java.awt.AWTException;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.ImageIcon;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.text.DefaultCaret;

/**
 *
 * @author Administrador
 */
public class VentanaPrincipal extends javax.swing.JFrame implements WindowListener {

    private static VentanaPrincipal instancia;

    /** Creates new form VentanaPrincipal */
    public VentanaPrincipal() {
        initComponents();
        this.setTitle("Productos Metalúrgicos S.A.");
        this.setSize(800, 500);
        this.setLocationRelativeTo(null);
        addWindowListener(this);
        setIconImage(new ImageIcon(this.getClass().getResource(
                "/com/proffline/imagenes/main_icon.png")).getImage());
        instancia = this;
        iniciar();
    }

    private void iniciar() {
        ProgramadorTareas programadorTareas = new ProgramadorTareas();
        programadorTareas.activarTiempoConexion();
    }

    public static VentanaPrincipal obtenerInstancia() {
        if (instancia == null) {
            instancia = new VentanaPrincipal();
        }
        return instancia;
    }

    public void establecerTextoABarraDeProgresoParcial(String texto) {
        progresoParcial.setString(texto);
    }

    public void agregarTextoAEditorConsola(String texto) {
        log = texto;
        edtConsola.setText(log);
        DefaultCaret caret = (DefaultCaret) edtConsola.getCaret();
        caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
    }
    public String log = "";

    public String obtenerTextoDeEditorConsola() {
        if (log.length() > 6) {
            return log.substring(0, log.length() - 7);
        } else {
            return log;
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        pnlBotones = new javax.swing.JPanel();
        btnLimpiar = new javax.swing.JButton();
        scrllConsola = new javax.swing.JScrollPane();
        edtConsola = new javax.swing.JEditorPane();
        pnlEstado = new javax.swing.JPanel();
        pnlProgreso = new javax.swing.JPanel();
        progresoTotal = new javax.swing.JProgressBar();
        progresoParcial = new javax.swing.JProgressBar();
        pnlEtiquetas = new javax.swing.JPanel();
        lblSincronizacionTotal = new javax.swing.JLabel();
        lblSincronizacionParcial = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        btnLimpiar.setText("Limpiar");
        btnLimpiar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnLimpiarActionPerformed(evt);
            }
        });
        pnlBotones.add(btnLimpiar);

        getContentPane().add(pnlBotones, java.awt.BorderLayout.PAGE_START);

        scrllConsola.setBackground(new java.awt.Color(0, 0, 0));
        scrllConsola.setBorder(null);

        edtConsola.setBackground(new java.awt.Color(0, 0, 0));
        edtConsola.setBorder(javax.swing.BorderFactory.createEmptyBorder(4, 4, 4, 4));
        edtConsola.setContentType("text/html");
        edtConsola.setEditable(false);
        edtConsola.setForeground(new java.awt.Color(255, 255, 255));
        edtConsola.setText("");
        scrllConsola.setViewportView(edtConsola);

        getContentPane().add(scrllConsola, java.awt.BorderLayout.CENTER);

        pnlEstado.setBorder(javax.swing.BorderFactory.createEmptyBorder(2, 2, 2, 2));
        pnlEstado.setLayout(new java.awt.BorderLayout(4, 4));

        pnlProgreso.setLayout(new java.awt.GridLayout(2, 1, 4, 4));

        progresoTotal.setStringPainted(true);
        pnlProgreso.add(progresoTotal);

        progresoParcial.setStringPainted(true);
        pnlProgreso.add(progresoParcial);

        pnlEstado.add(pnlProgreso, java.awt.BorderLayout.CENTER);

        pnlEtiquetas.setLayout(new java.awt.GridLayout(2, 1, 4, 4));

        lblSincronizacionTotal.setText("Sincronización total:");
        pnlEtiquetas.add(lblSincronizacionTotal);

        lblSincronizacionParcial.setText("Sincronización por tabla:");
        pnlEtiquetas.add(lblSincronizacionParcial);

        pnlEstado.add(pnlEtiquetas, java.awt.BorderLayout.LINE_START);

        getContentPane().add(pnlEstado, java.awt.BorderLayout.PAGE_END);

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void btnLimpiarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLimpiarActionPerformed
    edtConsola.setText("");
    log = "";
}//GEN-LAST:event_btnLimpiarActionPerformed

    public void setModoProgresoParcial(final boolean modo) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                progresoParcial.setIndeterminate(modo);
            }
        });

    }

    public void setMaximoProgresoTotal(final int maximoValor) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                progresoTotal.setMaximum(maximoValor);
            }
        });

    }

    public void setMaximoProgresoParcial(final int maximoValor) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                progresoParcial.setMaximum(maximoValor);
            }
        });

    }

    public void setProgresoTotal(final int porcentajeAvance) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                progresoTotal.setValue(porcentajeAvance);
            }
        });

    }

    public void setProgresoParcial(final int porcentajeParcial) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                progresoParcial.setValue(porcentajeParcial);
            }
        });

    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {

        try {
            UIManager.setLookAndFeel(
                    UIManager.getSystemLookAndFeelClassName());
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Windows Classic".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (UnsupportedLookAndFeelException e) {
            // handle exception
        } catch (ClassNotFoundException e) {
            // handle exception
        } catch (InstantiationException e) {
            // handle exception
        } catch (IllegalAccessException e) {
            // handle exception
        }
        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new VentanaPrincipal().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnLimpiar;
    private javax.swing.JEditorPane edtConsola;
    private javax.swing.JLabel lblSincronizacionParcial;
    private javax.swing.JLabel lblSincronizacionTotal;
    private javax.swing.JPanel pnlBotones;
    private javax.swing.JPanel pnlEstado;
    private javax.swing.JPanel pnlEtiquetas;
    private javax.swing.JPanel pnlProgreso;
    private javax.swing.JProgressBar progresoParcial;
    private javax.swing.JProgressBar progresoTotal;
    private javax.swing.JScrollPane scrllConsola;
    // End of variables declaration//GEN-END:variables
    private SystemTray tray = null;

    @Override
    public void windowOpened(WindowEvent e) {
    }

    @Override
    public void windowClosing(WindowEvent e) {
        if (SystemTray.isSupported() && tray == null) {
            tray = SystemTray.getSystemTray();
            ImageIcon imagenIcono = new javax.swing.ImageIcon(getClass().getResource("/com/proffline/imagenes/main_icon.gif"));
            MouseListener mouseListener = new MouseListener() {

                @Override
                public void mouseClicked(MouseEvent e) {
                }

                @Override
                public void mouseEntered(MouseEvent e) {
                }

                @Override
                public void mouseExited(MouseEvent e) {
                }

                @Override
                public void mousePressed(MouseEvent e) {
                }

                @Override
                public void mouseReleased(MouseEvent e) {
                }
            };
            ActionListener escuchadorSalir = new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    System.exit(0);
                }
            };
            PopupMenu popup = new PopupMenu();
            MenuItem item = new MenuItem("Salir");
            item.addActionListener(escuchadorSalir);
            popup.add(item);
            //iniciamos el objeto TrayIcon
            final TrayIcon iconoSystemTray = new TrayIcon(imagenIcono.getImage(), "Sincronización de base de datos proffline", popup);
            //este tipo de listener captura el doble click sobre el icono
            ActionListener accionMostrarMensaje = new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    instancia.setVisible(true);
                }
            };
            iconoSystemTray.setImageAutoSize(true);
            iconoSystemTray.addActionListener(accionMostrarMensaje);
            iconoSystemTray.addMouseListener(mouseListener);
            try {
                tray.add(iconoSystemTray);
            } catch (AWTException ex) {
                System.err.println(ex.getMessage());
            }
        }
    }

    @Override
    public void windowClosed(WindowEvent e) {
    }

    @Override
    public void windowIconified(WindowEvent e) {
    }

    @Override
    public void windowDeiconified(WindowEvent e) {
    }

    @Override
    public void windowActivated(WindowEvent e) {
    }

    @Override
    public void windowDeactivated(WindowEvent e) {
    }
}
